use iced::{Button, Column, Container, Element, Length, Text, TextInput, button, text_input};

use crate::ui::consts;

use super::{Screen, ScreenState};

#[derive(Default)]
pub struct Login {
    name: String,

    name_input: text_input::State,
    ok: button::State,
}

#[derive(Debug, Clone)]
pub enum Message {
    NameChange(String),
    NameSet,
}

impl Login {
    pub fn new() -> Self {
        Self {
            name: "Temp".into(),
            ..Default::default()
        }
    }
    pub fn title(&self) -> String {
        format!("{} - Login", consts::APP_NAME)
    }

    pub fn update(&mut self, message: Message) -> ScreenState {
        match message {
            Message::NameChange(val) => {
                self.name = val;
                ScreenState::Keep
            }
            Message::NameSet => {
                let name = self.name.trim();
                if !name.is_empty() {
                    ScreenState::SwitchTo(Screen::Chat, name.into())
                } else {
                    ScreenState::Keep
                }
            }
        }
    }

    pub fn view(&mut self) -> Element<Message> {
        let id = Text::new("Login your ID").width(Length::Fill);

        let name_input = TextInput::new(
            &mut self.name_input,
            "Login your name",
            &self.name,
            Message::NameChange,
        )
        .padding(5)
        .on_submit(Message::NameSet);

        let ok = Button::new(
            &mut self.ok,
            Text::new("Ok").horizontal_alignment(iced::HorizontalAlignment::Center))
            .min_width(100)
            .on_press(Message::NameSet);

        let layout = Column::new()
            .push(id)
            .spacing(10)
            .push(name_input)
            .spacing(3)
            .push(ok)
            .align_items(iced::Align::Center)
            .padding(20);

        Container::new(layout)
            .width(Length::Fill)
            .height(Length::Fill)
            .center_y()
            .into()
    }
}